<?php

namespace App\Http\Controllers\Mobile\Personal;
use App\Facades\Site;
use App\Http\Requests\Common\Captcha\SmsCodeRequest;
use Illuminate\Http\Request;
use App\Models\Personal\PersonalUser;
use Style,Sms;
use Illuminate\Hashing\BcryptHasher as Hasher;

class RegisterController extends CommonController{
    protected $hasher;
    public function __construct(Hasher $hasher){
        $this->hasher = $hasher;
    }

    /**
     * @return mixed
     */
    public function index(){
        return Style::view('personal.index');
    }

    /**
     * ajax验证用户名
     * @param Request $request
     */
    public function ajaxUsername(Request $request){
        $username = $request->input('username');
        $result = PersonalUser::where('username', $username)->first();
        //判断用户名是不是被注册
        echo ($result) ? 'false' : 'true';
    }

    /**
     * ajax验证短线验证
     * @param Request $request
     */
    public function ajaxSmsUrl(Request $request){
        $mobCode = $request->input('mobCode');
        $mobile = $request->input('mobile');
        //判断手机是不是被注册
        echo ($mobCode == session('mobile_verification_code') && $mobile == session('mobile_verification')) ? 'true' : 'false';
    }

    /**
     * ajax验证手机号码注册
     * @param Request $request
     */
    public function ajaxMobile(Request $request){
        $mobile = $request->input('mobile');
        $result = PersonalUser::where('mobile', $mobile)->first();
        //判断手机不是被注册
        echo ($result) ? 'false' : 'true';
    }

    /**
     * 获取短信验证码注册
     * @param SmsCodeRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function ajaxMobCode(SmsCodeRequest $request){
        $mobileNum = $request->input('mobile');
        $result = PersonalUser::where('mobile', $mobileNum)->orWhere('username', $mobileNum)->first();
        if ($result) {
            return response()->json(['status' => '2', 'msg' => '此手机号码已经注册']);
        } else {
            //设置session
            $request->session()->put('mobile_verification_code', rand(1000, 9999));
            $request->session()->put('mobile_verification', $mobileNum);
            //模板参数
            $smsParam = array(
                'product' => Site::get('webname'),
                'code'    => (string)session('mobile_verification_code')
            );
            $sendResult = Sms::codeSend($mobileNum, $smsParam);
            //返回对象
            if (is_object(@$sendResult->result) && $sendResult->result->err_code == '0') {
                return response()->json(['status' => '1', 'msg' => '发送短信成功']);
            } else {
                return response()->json(['status' => '0', 'msg' => '一分钟之内只能发一次,或者您发送的次数已经达到上限']);
            }
        }
    }
}